/*
 * @Author: 生俊甫 1758142861@qq.com
 * @Date: 2024-06-06 17:00:08
 * @LastEditors: 生俊甫 1758142861@qq.com
 * @LastEditTime: 2024-06-06 18:04:48
 * @FilePath: /sjf/2024-project/2024_centos/source/log.hpp
 * @Description: 该文件是文集级别的日志信息
 */
#pragma once


#include <iostream>
#include <string>
#include <ctime>
#include <cstring>
#include <stdarg.h>
#include <unistd.h>

using namespace std;

#define LOG_NORMAL "./log/log.txt"
#define LOG_ERR "./log/log.error"
#define NUM 1024

enum
{
    USAGE_ERR = 11,
    SOCKET_ERR,
    BIND_ERR,
    LISTEN_ERR,
    EPOLL_ERR,
    CREATEVENTFD_ERR,
    READEVENTFD_ERR,
    WRITEEVENTFD_ERR,
    TIMERFD_ERR,
    READTIMERFD_ERR
};

#define DEBUG 0
#define NORMAL 1
#define WARNING 2
#define ERROR 3
#define FATAL 4

const char *to_levelstr(int level)
{
    switch (level)
    {
    case DEBUG:
        return "DEBUG";
    case NORMAL:
        return "NORMAL";
    case WARNING:
        return "WARNING";
    case ERROR:
        return "ERROR";
    case FATAL:
        return "FATAL";
    default:
        return nullptr;
    }
}

const char* to_time()
{
    std::string time_now = "";
   // 基于当前系统的当前日期/时间
   time_t now = time(0);
   tm *ltm = localtime(&now);
   time_now += to_string(1900 + ltm->tm_year);
   time_now += "年";
   time_now += to_string(1 + ltm->tm_mon);
   time_now += "月";
   time_now += to_string(ltm->tm_mday);
   time_now += "日";
   time_now += to_string(ltm->tm_hour);
   time_now += "时";
   time_now += to_string(ltm->tm_min);
   time_now += "分";
   time_now += to_string(ltm->tm_sec);
   time_now += "秒";
   return time_now.c_str();
}

void logMessage(int level, const char *format, ...)
{
    //[日志等级][事件][pid][message]
    char logprefix[NUM];
    snprintf(logprefix, sizeof(logprefix), "[%s][%s][pid:%d]", to_levelstr(level), to_time(), getpid());

    char logcontent[NUM];
    va_list arg;
    va_start(arg,format);
    vsnprintf(logcontent,sizeof(logcontent),format,arg);

    //向文件中输出日志信息
    FILE *log = fopen(LOG_NORMAL, "a");
    FILE *err = fopen(LOG_ERR, "a");
    if (log != nullptr && err != nullptr)
    {
        FILE* curr = nullptr;
        if(level == DEBUG || level == NORMAL || level == WARNING) curr = log;
        if(level == ERROR || level == FATAL) curr = err;
        if(curr) fprintf(curr,"%s%s\n",logprefix,logcontent);
        fclose(log);
        fclose(err);
    }
}
//#endif